package kr.hkit.androidcomplete01.ch12;

import java.util.ArrayList;

import kr.hkit.androidcomplete01.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ListAddDelSingleChoice extends Activity {

	private ArrayList<String> arItems;
	private ArrayAdapter<String> adapter;
	private ListView listView;
	private EditText mEdit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch12_listadddelsinglechoice);

		arItems = new ArrayList<String>();
		arItems.add("First");
		arItems.add("Second");
		arItems.add("Third");

		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_single_choice, arItems);

		listView = (ListView) findViewById(R.id.adddel_list);
		listView.setAdapter(adapter);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) { // 리스트 항목 선택시
				Toast.makeText(getApplicationContext(),
						adapter.getItem(position), Toast.LENGTH_LONG).show();
			}
		});

		mEdit = (EditText) findViewById(R.id.newItem);

	}

	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.btnAdd:
			String str = mEdit.getText().toString().trim();
			if (str.length() != 0) {

				arItems.add(str); // 원본 추가
				mEdit.setText(""); // 리스트뷰 수정
			}
			break;
		case R.id.btnDel:
			int selPos = listView.getCheckedItemPosition();
			if (selPos != ListView.INVALID_POSITION) {
				arItems.remove(selPos); // arraylist에서 삭제
				listView.clearChoices(); // 리스트뷰에서 선택한거 클리어. 없애기
			}
			break;
		}
		adapter.notifyDataSetChanged(); // 원본 바뀌었는지 알리기
	}

}
